<?php

namespace app\common\command;

use app\common\library\Hash;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Log;
use think\Db;
use app\common\library\Config;
use think\helper\Time;

class Sys extends Command
{


    //命令描述
    protected function configure()
    {
        $this->setName('Sys')->setDescription('sys run');
    }

    //所要执行的命令
    protected function execute(Input $input, Output $output)
    {
        // Cache::clear();
        Config::config();

        //创建库
        $this->create_db();
        //修改用户名密码
        $this->upuser();
        //删除到期项目数据库
        $this->del_db();
        //项目微信更新token
        $this->re_token();
        //申请小程序
        $this->minapp();


    }





    /**
     * 获取 申请小程序
     */

    function minapp()
    {
        echo 'minapp ' . "\r\n";
        $list = DB::name('minapp')
            ->where('status', 1)
            ->select();
        $component_access_token = DB::name('config')->where('id', 112)->value('value');
       // dump($component_access_token);
        $host = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token=' . $component_access_token;
        foreach ($list as $item) {

            $data = [];
            $data['name'] = $item['name'];
            $data['code'] = $item['code'];
            $data['code_type'] = $item['code_type'];
            $data['legal_persona_wechat'] = $item['legal_persona_wechat'];
            $data['legal_persona_name'] = $item['legal_persona_name'];
            $data['component_phone'] = $item['component_phone'];
            dump($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $host);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            $tmpInfo = curl_exec($ch);
            $re = json_decode($tmpInfo, TRUE);
             dump($re);
            if (curl_errno($ch)) {
                dump(json_encode(curl_errno($ch)));
                // dump(curl_error($ch));
                // \Think\Log::write(jcurl_errno($ch), 'INFO');
                // \think\facade\Log::write(json_encode(curl_errno($ch)), 'WX_MESSAGE_ERROE');
               // return 1;
            }
            \think\facade\Log::write($re, 'WX_MESSAGE');
            curl_close($ch);
            if (isset($re['errcode'])) {
                $info='';
                $status=2;
                switch ($re['errcode']){
                    case 0:
                        $info='成功';
                        break;
                    case -1:
                        $info='非法 action 参数';
                        break;
                    case 89249:
                        $info='该主体已有任务执行中，距上次任务 24h 后再试';
                        break;
                    case 89247:
                        $info='内部错误';
                        break;
                    case 86004:
                        $info='无效微信号';
                        break;
                    case 61070:
                        $info='法人姓名与微信号不一致';
                        break;
                    case 89248:
                        $info='企业代码类型无效，请选择正确类型填写';
                        break;
                    case 89250:
                        $info='未找到该任务';
                        break;
                    case 89251:
                        $info='待法人人脸核身校验';
                        break;
                    case 89252:
                        $info='法人&企业信息一致性校验中';
                        break;
                    case 89253:
                        $info='缺少参数';
                        break;
                    case 89254:
                        $info='第三方权限集不全，补全权限集全网发布后生效';
                        break;
                    default:
                        $status=1;
                        $info=$re['errcode'];
                }

                DB::name('minapp')->where('id', $item['id'])->update(['status'=>$status,'info'=>$info]);
            }

        }


    }

    /**
     * 获取 component_access_token
     */

    function re_token()
    {
        $list = DB::view('product_run', 'id,status')
            ->view('product_wx', 'product_run_id,authorizer_appid,authorizer_refresh_token,authorizer_access_token,update_time', 'product_run.id=product_wx.product_run_id')
            ->where('status', 1)
            ->select();

        $component_access_token = DB::name('config')->where('id', 112)->value('value');
        $component_appid=DB::name('config')->where('id', 107)->value('value');
        $host = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $component_access_token;
        foreach ($list as $item) {
            $data = [];
            $data['component_appid'] = $component_appid;
            $data['authorizer_appid'] = $item['authorizer_appid'];
            $data['authorizer_refresh_token'] = $item['authorizer_refresh_token'];
           // dump($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $host);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            $tmpInfo = curl_exec($ch);
            $re = json_decode($tmpInfo, TRUE);
            //dump($re);
            if (curl_errno($ch)) {
                // dump(curl_error($ch));
                // \Think\Log::write(jcurl_errno($ch), 'INFO');
                // \think\facade\Log::write(json_encode(curl_errno($ch)), 'WX_MESSAGE_ERROE');
            }

            \think\facade\Log::write($re, 'WX_MESSAGE');
            curl_close($ch);
            if (isset($re['authorizer_access_token'])) {
                $info = [];
                $info['authorizer_access_token'] = $re['authorizer_access_token'];
                //$info['authorizer_refresh_token'] = $re['authorizer_refresh_token'];
                $info['update_time'] = time();
                DB::name('product_wx')->where('product_run_id', $item['id'])->update($info);
            }


        }


    }


    protected function create_db()
    {
        echo 'c_pro' . "\r\n";
        $this->pro();
    }

    protected function del_db()
    {
        echo 'd_pro' . "\r\n";
        $this->del_pro();
    }

    //项目管理软件
    function pro()
    {
        //要创建的列表
        $list = DB::name('product_run')->where('readmin', 1)->where('product_id', 10)->select();
        //
        $_sql = file_get_contents('sql/project200321.sql');
        $_arr = explode(';', $_sql);
        foreach ($list as $info) {
            Db::execute('CREATE DATABASE IF NOT EXISTS u' . $info['id'] . ' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;');
            $db = [
                // 数据库类型
                'type' => 'mysql',
                // 服务器地址
                'hostname' => 'rm-2zea426o72962o97z125010.mysql.rds.aliyuncs.com',
                // 数据库名
                'database' => 'u' . $info['id'],
                // 用户名
                'username' => 'weibuyun',
                // 密码
                'password' => 'Wei@#$1209C!=',
                // 数据库编码默认采用utf8
                'charset' => 'utf8',
            ];
            //恢复数据表及必要数据
            foreach ($_arr as $key => $_value) {
                if ($_value) {
                    //echo $key.'='.$_value."\r\n";
                    Db::connect($db)->execute($_value . ';');
                }
            }
            //写入设定管理员
            // dump($data);
            DB::name('product_run')->where('id', $info['id'])->update(['readmin' => 2]);
        }

    }

    //项目管理软件

    function del_pro()
    {
        //要创建的列表
        $list = DB::name('product_run')->where('e_time', '<=', time())->select();
        //
        foreach ($list as $info) {
            if ($info['e_time'] < (time() - 86400 * 30)) {
                $data['status'] = 5;
                $data['readmin'] = 4;
                if ($info['status'] < 5) {
                    Db::execute('drop DATABASE u' . $info['id'] . ';');
                }
            } elseif ($info['e_time'] > (time() - 86400 * 10)) {
                $data['status'] = 4;
            } else {
                $data['status'] = 2;
            }
            DB::name('product_run')->where('id', $info['id'])->update($data);
        }

    }

    function upuser()
    {
        echo 'up_pro' . "\r\n";
        //要创建的列表
        $list = DB::name('product_run')->where('readmin', 2)->where('product_id', 10)->select();
        //
        //dump($list);
        foreach ($list as $info) {
            $db = [
                // 数据库类型
                'type' => 'mysql',
                // 服务器地址
                'hostname' => 'rm-2zea426o72962o97z125010.mysql.rds.aliyuncs.com',
                // 数据库名
                'database' => 'u' . $info['id'],
                // 用户名
                'username' => 'weibuyun',
                // 密码
                'password' => 'Wei@#$1209C!=',
                // 数据库编码默认采用utf8
                'charset' => 'utf8',
            ];
            $data['username'] = $info['username'];
            $data['nickname'] = $data['username'];
            $data['password'] = Hash::hash($info['password']);
            Db::connect($db)->name('admin')->where('id', 1)->update($data);
            DB::name('product_run')->where('id', $info['id'])->update(['readmin' => 3]);
        }

    }
}